import axios from 'axios';
import socketClient from 'socket.io-client';

const socket = socketClient('ws://localhost:8888');

const MSG_LIST = 'MSG_LIST';//消息列表
const MSG_RECV = 'MSG_RECV';//收到的消息
const MSG_READ = 'MSG_READ';//未读消息

const initState = {
    msgLst:[],
    users:{},
    unread:0
};

export const msgReducer = (state=initState,action) => {
    switch(action.type) {
        case MSG_LIST://获取消息列表
        return {...state,users:action.payload.users,msgLst:action.payload.msgList,unread:action.payload.msgList.filter(v => !v.read).length}//过滤掉read状态为true的消息
        case MSG_RECV://获取回复消息
        return {...state,unread:state.unread+1,msgLst:[...state.msgLst,action.payload]}
        case MSG_READ:
        return {}
        default :
        return state
    }
}


function msgList(data) {
    return {type:MSG_LIST,payload:data};
}
function msgRecv(data) {
    return {type:MSG_RECV,payload:data}
}


// 请求消息列表
export const getMsgList = (chaterId) => {
    return dispatch => {
        axios.get(`/user/getMsgList?chaterId=${chaterId}`).then(res => {
            console.log(res);
            if(res.status === 200 && res.data.msgList && res.data.users) {
                dispatch(msgList(res.data));
            }
        })
    }
}
// 捕捉消息返回函数
export const getMsgRecv = () => {
    return dispatch => {
        socket.on('msgRecv',(data) => {
            // console.log(data);
            if(data) {
                dispatch(msgRecv(data));
            }            
        })
    }
    
}

// 发送信息函数
export const emitMsg = ({from,to,msg}) => {
    // console.log({from,to,msg})
    return dispatch => {
        socket.emit('chatMsg',{from,to,msg});
    }
}